<template>
  <view class="container">
    <!-- <view class="header">
      <view class="back-button" @click="goBack">
        <text class="back-icon">←</text>
      </view>
      <view class="figure-info">
        <text class="figure-name">{{ currentFigure.name }}</text>
        <text class="figure-title">{{ currentFigure.title }}</text>
      </view>
    </view> -->

    <scroll-view class="chat-container" :style="{ height: containerHeight + 'px' }" scroll-y="true"
      :scroll-top="scrollTop" id="chatContainer">
      <view class="message-wrapper">
        <!-- Add clear history button at the top when there are messages -->
        <view class="clear-history-button" v-if="messages.length > 1" @click="clearChatHistory">
          <text class="clear-history-text">清除对话记录</text>
        </view>

        <view v-for="(message, index) in messages" :key="index" class="message-item" :class="message.type">
          <image class="message-avatar"
            :src="message.type === 'figure' ? currentFigure.avatar : '/static/user-avatar.png'"></image>
          <view class="message-content">
            <!-- Use text for user messages and rich-text with markdown for figure messages -->
            <text v-if="message.type === 'user'">{{ message.content }}</text>
            <rich-text v-else :nodes="renderMarkdown(message.content)" class="markdown-content"></rich-text>
          </view>
        </view>

        <!-- Show typing indicator for non-streaming loading -->
        <view class="typing-indicator" v-if="isLoading && !isStreaming">
          <view class="typing-dot"></view>
          <view class="typing-dot"></view>
          <view class="typing-dot"></view>
        </view>
      </view>
    </scroll-view>

    <view class="bottom-container">
      <!-- Add suggested questions section -->
      <view class="input-preset" v-if="suggestedQuestions && suggestedQuestions.length > 0">
        <scroll-view scroll-x="true" class="preset-scroll">
          <view class="preset">
            <view v-for="(question, index) in suggestedQuestions.slice(0, 3)" 
                  :key="index" 
                  class="preset-item"
                  @click="handleQuestionClick(question)">
              {{ question.text }}
            </view>
            <view class="preset-item" @click="generateSuggestedQuestions" 
                  v-if="suggestedQuestions && suggestedQuestions[0] && suggestedQuestions[0].text !== '小莒正在思考中..'">
              换一批
            </view>
          </view>
        </scroll-view>
      </view>

      <view class="input-area">
        <textarea class="input-box" v-model="userInput" :ref="textArea" @linechange="handleTextareaHeightChange"
          placeholder="输入您的问题..." :disabled="isLoading || isStreaming" auto-height></textarea>
        <view class="send-button" @click="sendMessage"
          :class="{ 'disabled': isLoading || isStreaming || !userInput.trim() }">
          <text class="send-text">发送</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { defineComponent, ref, reactive, onMounted, nextTick, onBeforeUnmount } from 'vue';
import { marked } from 'marked';
import { Prism } from 'prismjs';

export default defineComponent({
  setup() {
    const figures = reactive([
      {
        id: 1,
        name: '管仲',
        title: '春秋时期政治家',
        avatar: '/static/shikong/guanzhong.jpg',
        description: '春秋时期齐国宰相，莒县人，辅佐齐桓公成为五霸之首，制定了著名的"弱干强枝"策略。',
        prompt: '我是管仲（约公元前723年-公元前645年），字夷吾，莒县人，春秋时期著名的政治家和思想家。我辅佐齐桓公成为春秋五霸之首，实施"尊王攘夷"政策，推行"轻关易道"的经济政策，壮大齐国国力。我的政治思想被后人整理为《管子》一书，对后世产生了深远影响。我强调法治和经济在治国中的重要性，认为"仓廪实而知礼节，衣食足而知荣辱"。我深信合理的制度是国家繁荣的基础，而非单纯依靠君主个人的贤明。如今穿越时空与你对话，请问有何见教？'
      },
      {
        id: 2,
        name: '刘勰',
        title: '南北朝文学批评家',
        avatar: '/static/shikong/liuxie.jpg',
        description: '南北朝时期文学理论家，著有《文心雕龙》，被誉为中国古代文学理论的集大成者。',
        prompt: '我是刘勰（约公元465年-约公元521年），南北朝时期杰出的文学理论家、评论家。我著有《文心雕龙》，这是中国古代最重要的文学理论著作之一，被誉为"文学之经"。我在书中系统地阐述了中国古代文学的起源、发展、体裁、风格、创作方法等理论问题，体现了深刻的文学见解和美学思想。我的理论对中国古代文学创作产生了深远影响，被后人尊为文学理论的开拓者和集大成者。今日有幸与你交流，愿与你探讨文学艺术的奥妙与真谛。'
      },
      {
        id: 3,
        name: '左思',
        title: '晋代文学家、诗人',
        avatar: '/static/shikong/zuosi.jpg',
        description: '西晋著名文学家、诗人，莒县人，创作了《三都赋》等脍炙人口的作品，影响深远。',
        prompt: '我是左思（约公元250年-约公元305年），字太冲，莒县人，西晋著名文学家、诗人。我创作了《三都赋》，描绘魏、蜀、吴三国都城的繁华景象，被誉为"才高八斗"。我著述《咏史》等诗篇，以史为鉴，讽喻现实。我耗时十年完成《三都赋》，"洛阳纸贵"的典故即源于此。我品性高洁，不慕荣利，曾以"肉食者鄙，未能远谋"讽刺当权贵族。我的作品辞藻华丽而不失内涵，被后世推崇为"太冲体"。现在穿越时空，愿与你谈文论道。'
      },
      {
        id: 4,
        name: '姜亮',
        title: '明代诗人、书法家',
        avatar: '/static/shikong/jiangliang.jpg',
        description: '明代著名诗人、书法家，莒县人，擅长山水诗词，行书、楷书功底深厚，著有《姜氏集》。',
        prompt: '我是姜亮（1524年-1591年），字明仲，号晴峰，莒县人，明代中期著名的诗人、书法家。我擅长创作山水诗词，风格清新自然，意境高远。我的书法功底深厚，尤擅行书与楷书，笔法苍劲有力，风格独特。我一生创作颇丰，著有《姜氏集》，内容包括诗词、书论及日常笔记等。我生活于明朝中后期，亲历了社会变革与思想交融的时代，作品中既有对自然山水的赞美，也有对社会现实的思考。今日有幸穿越时空与您对话，愿分享我对文学艺术的见解。'
      }
    ]);
    const containerHeight = ref(0);     // 动态计算的容器高度
    const inputAreaHeight = ref(0);    // 初始假设输入框高度为 55px
    const currentFigure = ref({});
    const messages = ref([]);
    const userInput = ref('');
    const isLoading = ref(false);
    const isStreaming = ref(false);
    const scrollTop = ref(0);
    const textArea = ref(null)
    const localStoragePrefix = 'shikong_chat_';
    let assistantMessageIndex = -1;

    const userProfile = ref({ theme: '' });
    const trendingTopics = ref([]);
    const suggestedQuestions = ref([]);

    function calcContainerHeight() {
      const systemInfo = uni.getSystemInfoSync();
      const screenHeight = systemInfo.windowHeight; // 屏幕高度
      const headerHeight = 0; // 头部高度（根据实际值调整，单位px）
      inputAreaHeight.value = 40 + 30;

      // 动态计算中间区域高度
      containerHeight.value = screenHeight - headerHeight - inputAreaHeight.value - 15;
      console.log("containerHeight:" + containerHeight.value)
    }

    // textarea 高度变化时触发（通过 @linechange 事件）
    function handleTextareaHeightChange(e) {
      inputAreaHeight.value = e.detail.height + 30; // 30px 是输入框的 padding 等补偿值
      console.log("input lines changed" + inputAreaHeight.value)
      calcContainerHeight();
    }

    // Initialize marked library
    function initMarked() {
      marked.setOptions({
        renderer: new marked.Renderer(),
        highlight: function (code, lang) {
          if (Prism && Prism.languages[lang]) {
            return Prism.highlight(code, Prism.languages[lang], lang);
          } else {
            return code;
          }
        },
        pedantic: false,
        gfm: true,
        breaks: true,
        sanitize: false,
        smartLists: true,
        smartypants: false,
        xhtml: false
      });
    }

    // Load initial data
    async function loadInitialData() {
      await Promise.all([
        // fetchUserProfile(),
        fetchTrendingTopics()
      ]);
      await generateSuggestedQuestions();
    }

    // Call initMarked on component mount
    onMounted(() => {
      initMarked();
      calcContainerHeight();
      loadInitialData();
    });

    // Load the initial data based on the passed id
    function onLoad(options) {
      const figureId = parseInt(options.id) || 1;
      currentFigure.value = figures.find(f => f.id === figureId) || figures[0];

      loadChatHistory();

      // If it's a new conversation, add the first message from the historical figure
      if (messages.value.length === 0) {
        messages.value.push({
          type: 'figure',
          content: currentFigure.value.prompt
        });

        // Save this initial message
        saveChatHistory();
      }

      nextTick(() => {
        scrollToBottom();
      });
    }

    // Handle going back
    function goBack() {
      uni.navigateBack();
    }

    // Load chat history from storage - ensure we correctly load the history
    function loadChatHistory() {
      try {
        // First check for interrupted streams
        if (checkForInterruptedStream()) {
          return; // We've already loaded the recovered state
        }

        const key = `${localStoragePrefix}${currentFigure.value.id}`;
        const history = uni.getStorageSync(key);
        if (history) {
          const parsedHistory = JSON.parse(history);
          if (Array.isArray(parsedHistory) && parsedHistory.length > 0) {
            console.log(`Loaded ${parsedHistory.length} messages from history`);
            messages.value = parsedHistory;
          } else {
            console.log('History was empty, using default prompt');
            messages.value = [];
          }
        } else {
          console.log('No history found, using default prompt');
          messages.value = [];
        }
      } catch (e) {
        console.error('加载聊天记录失败', e);
        messages.value = [];
      }
    }

    // Save chat history to storage - make sure it properly stores all messages
    function saveChatHistory() {
      try {
        const key = `${localStoragePrefix}${currentFigure.value.id}`;
        const serializedMessages = JSON.stringify(messages.value);
        uni.setStorageSync(key, serializedMessages);
        console.log(`Chat history saved: ${messages.value.length} messages`);
      } catch (e) {
        console.error('保存聊天记录失败', e);
      }
    }

    // Add a function to handle periodic saving during streaming
    let saveHistoryTimer = null;
    function startPeriodicSaving() {
      // Clear any existing timer
      if (saveHistoryTimer) {
        clearInterval(saveHistoryTimer);
      }

      // Save history every 5 seconds during streaming
      saveHistoryTimer = setInterval(() => {
        if (isStreaming.value && assistantMessageIndex >= 0) {
          // Save the current state with partial flag
          try {
            const key = `${localStoragePrefix}${currentFigure.value.id}_stream`;
            // Add a flag to the messages to indicate they contain a partial response
            const streamMessages = [...messages.value];
            streamMessages[assistantMessageIndex] = {
              ...streamMessages[assistantMessageIndex],
              isPartial: true
            };
            uni.setStorageSync(key, JSON.stringify(streamMessages));
            console.log('Saved intermediate streaming state');
          } catch (e) {
            console.error('保存中间状态失败', e);
          }
        }
      }, 5000);
    }

    function stopPeriodicSaving() {
      if (saveHistoryTimer) {
        clearInterval(saveHistoryTimer);
        saveHistoryTimer = null;
      }

      // Clean up streaming state
      try {
        const key = `${localStoragePrefix}${currentFigure.value.id}_stream`;
        uni.removeStorageSync(key);
      } catch (e) {
        console.error('清理临时状态失败', e);
      }
    }

    // Check for interrupted streams when loading
    function checkForInterruptedStream() {
      try {
        const streamKey = `${localStoragePrefix}${currentFigure.value.id}_stream`;
        const streamData = uni.getStorageSync(streamKey);

        if (streamData) {
          // We have an interrupted stream state
          const streamMessages = JSON.parse(streamData);

          // Find the message which was marked as partial
          for (let i = 0; i < streamMessages.length; i++) {
            if (streamMessages[i].isPartial) {
              // Remove the partial flag
              delete streamMessages[i].isPartial;
              break;
            }
          }

          // Update our messages
          messages.value = streamMessages;

          // Clean up the stream state
          uni.removeStorageSync(streamKey);

          // Save the recovered state
          saveChatHistory();

          console.log('Recovered from interrupted stream');
          return true;
        }
      } catch (e) {
        console.error('检查中断状态失败', e);
      }
      return false;
    }

    // Render Markdown content - following zhixun/index.vue pattern
    function renderMarkdown(content) {
      try {
        if (!content) return '';

        // Use marked to convert Markdown to HTML
        let html = marked.parse(content);

        // Return the HTML content
        return html;
      } catch (error) {
        console.error('Markdown渲染失败:', error);
        // Fallback to simple HTML if rendering fails
        return content.replace(/\n/g, '<br>');
      }
    }

    function throttle(func, wait) {
      let timeout = null;
      return function (...args) {
        const context = this;
        if (!timeout) {
          func.apply(context, args);
          timeout = setTimeout(() => {
            timeout = null;
          }, wait);
        }
      };
    }

    // Send a message
    async function sendMessage() {
      if (!userInput.value.trim() || isLoading.value || isStreaming.value) return;

      // Add user message
      messages.value.push({
        type: 'user',
        content: userInput.value.trim()
      });

      // Save history immediately after adding user message
      saveChatHistory();

      const userQuestion = userInput.value.trim();
      userInput.value = '';
      isLoading.value = true;

      nextTick(() => {
        scrollToBottom();
      });

      // Get dialogue history as context
      const history = messages.value
        .slice(-6) // Get last few messages as context
        .map(msg => `${msg.type === 'user' ? '用户' : currentFigure.value.name}: ${msg.content}`)
        .join('\n');

      try {
        const token = uni.getStorageSync('token') || '';

        // Add an empty figure message that will be filled by streaming content
        assistantMessageIndex = messages.value.length;
        messages.value.push({
          type: 'figure',
          content: '' // Empty content to be filled during streaming
        });

        // Create the prompt for the historical figure
        const promptData = {
          prompt: `以下是用户与${currentFigure.value.name}（${currentFigure.value.title}）的对话。
你需要以${currentFigure.value.name}的身份回答问题。
${currentFigure.value.name}的背景信息：${currentFigure.value.description}
回答时保持${currentFigure.value.name}的语气和性格特点，回答要有古代的韵味，但要让现代人能够理解。
如果问题与莒县历史、或者${currentFigure.value.name}的生平、思想、成就等相关，尽量提供详细准确的信息。
如果问题是现代问题，你可以以历史人物的视角来看待现代问题，可以适当表达惊奇和对现代事物的好奇。

历史对话：
${history}

用户: ${userQuestion}
${currentFigure.value.name}: `,
          apiKey: "juxianwenlv",
          stream: true
        };

        // Use streaming response
        isStreaming.value = true;
        startPeriodicSaving();

        // Set up streaming request
        const requestTask = uni.request({
          url: 'https://tushuoit.com/api/ju/deepseek/chat',
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'Authorization': token ? `Bearer ${token}` : ''
          },
          data: promptData,
          responseType: 'text',
          enableChunked: true,
          success: () => { },
          fail: (err) => {
            console.error('Streaming request failed', err);
            handleStreamingError();
          },
          complete: () => {
            isLoading.value = false;
            isStreaming.value = false;
            stopPeriodicSaving();
            console.log("streaming request stopped")
            // Check if we received any content
            if (messages.value[assistantMessageIndex].content.trim() === '') {
              messages.value[assistantMessageIndex].content = '抱歉，未能获取回答内容。';
            }

            // Save the final message state
            saveChatHistory();

            nextTick(() => {
              scrollToBottom();
            });
          }
        });

        // Handle streaming data
        requestTask.onChunkReceived((res) => {
          if (res && res.data) {
            try {
              // Convert binary data to text
              const uint8Array = new Uint8Array(res.data);
              let text = String.fromCharCode.apply(null, uint8Array);
              text = decodeURIComponent(escape(text));

              // Process SSE data chunks
              const lines = text.split('\n');
              for (const line of lines) {
                if (line.startsWith('data: ')) {
                  // Filter end marker
                  if (line === 'data: [DONE]') continue;

                  const jsonData = line.substring(6); // Remove "data: " prefix
                  try {
                    const data = JSON.parse(jsonData);
                    // Handle OpenAI/DeepSeek streaming format
                    if (data.choices && data.choices[0]) {
                      if (data.choices[0].delta && data.choices[0].delta.content) {
                        // Add new content to the current message
                        const chunk = data.choices[0].delta.content;
                        messages.value[assistantMessageIndex].content += chunk;
                      }
                      // Handle alternative API response formats
                      else if (data.choices[0].message && data.choices[0].message.content) {
                        const chunk = data.choices[0].message.content;
                        messages.value[assistantMessageIndex].content += chunk;
                      }

                      // Periodically scroll to bottom (throttle to avoid jank)
                      // if (Math.random() < 0.1) { // ~10% chance to scroll
                      //   nextTick(() => {
                      //     scrollToBottom();
                      //   });
                      // }

                    }
                    // Handle other possible formats
                    else if (data.data && data.data.text) {
                      messages.value[assistantMessageIndex].content += data.data.text;

                      // if (Math.random() < 0.1) {
                      //   nextTick(() => {
                      //     scrollToBottom();
                      //   });
                      // }
                    }
                    // 每 500ms 最多触发一次滚动
                    const throttledScroll = throttle(() => {
                      nextTick(scrollToBottom);
                    }, 500);
                    throttledScroll();
                  } catch (e) {
                    console.error('解析JSON块失败', e, jsonData);
                  }
                }
              }
            } catch (e) {
              console.error('处理数据块失败', e);
            }
          }
        });
      } catch (error) {
        console.error('Request failed', error);
        handleStreamingError();
      }
    }

    // Handle streaming errors - make sure to save after adding error message
    function handleStreamingError() {
      isLoading.value = false;
      isStreaming.value = false;
      stopPeriodicSaving();

      // If we have a pending message, update it with an error
      if (assistantMessageIndex >= 0 && messages.value[assistantMessageIndex]) {
        messages.value[assistantMessageIndex].content = '抱歉，时空隧道似乎出现了问题，无法回应您的问题。';
      } else {
        // Otherwise add a new error message
        messages.value.push({
          type: 'figure',
          content: '抱歉，时空隧道似乎出现了问题，无法回应您的问题。'
        });
      }

      // Save immediately
      saveChatHistory();

      nextTick(() => {
        scrollToBottom();
      });
    }

    // Scroll to bottom of chat
    function scrollToBottom() {
      setTimeout(() => {
        const query = uni.createSelectorQuery();
        query.select('#chatContainer').boundingClientRect();
        query.selectAll('.message-item').boundingClientRect();
        query.exec(res => {
          if (res[0] && res[1] && res[1].length) {
            let height = 0;
            res[1].forEach(item => {
              height += item.height;
            });
            scrollTop.value = height + 1000; // Ensure scroll to bottom
          }
        });
      }, 100);
    }

    // Add clearChatHistory function
    function clearChatHistory() {
      uni.showModal({
        title: '提示',
        content: '确定要清空所有聊天记录吗？',
        success: (res) => {
          if (res.confirm) {
            // Keep only the first welcome message
            const welcomeMessage = messages.value.length > 0 ? messages.value[0] : null;

            // Clear messages
            messages.value = [];

            // If we had a welcome message, restore it
            if (welcomeMessage && welcomeMessage.type === 'figure') {
              messages.value.push(welcomeMessage);
            } else {
              // If no welcome message was found, create one with the figure's prompt
              messages.value.push({
                type: 'figure',
                content: currentFigure.value.prompt
              });
            }

            // Save the cleared state
            saveChatHistory();

            uni.showToast({
              title: '聊天记录已清空',
              icon: 'success'
            });
          }
        }
      });
    }

    // Handle clicking a suggested question
    function handleQuestionClick(question) {
      if (question.text === '小莒正在思考中..') return;
      userInput.value = question.text;
      sendMessage();
    }

    // Generate new suggested questions based on conversation context
    function generateSuggestedQuestions() {
      const newQuestions = [
        { text: '你的主要思想是什么？' },
        { text: '你对教育有什么见解？' },
        { text: '你最难忘的经历是什么？' }
      ];
      suggestedQuestions.value = newQuestions;
    }

    // Lifecycle hook compatibility
    onMounted(() => {
      // Get the options from the page instance
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      const options = currentPage.options || {};

      // Initialize with the provided options
      onLoad(options);
    });

    // Ensure we clean up on unmount
    onBeforeUnmount(() => {
      stopPeriodicSaving();
    });

    // Fetch user profile
    async function fetchUserProfile() {
      try {
        const token = uni.getStorageSync('token') || '';
        const res = await uni.request({
          url: 'https://tushuoit.com/api/ju/users/me/profiles/theme',
          method: 'GET',
          header: {
            'Authorization': token ? `Bearer ${token}` : ''
          }
        });
        
        if (res.statusCode === 200 && res.data.code === 0) {
          userProfile.value = res.data.data || { theme: '' };
        } else {
          userProfile.value = { theme: '' };
        }
      } catch (error) {
        console.error('Failed to fetch user profile:', error);
        userProfile.value = { theme: '' };
      }
    }

    // Fetch trending topics
    async function fetchTrendingTopics() {
      try {
        const res = await uni.request({
          url: 'https://tushuoit.com/api/ju/trending/baidu',
          method: 'GET'
        });
        
        if (res.statusCode === 200 && res.data.code === 0) {
          trendingTopics.value = res.data.data || [];
        } else {
          trendingTopics.value = [];
        }
      } catch (error) {
        console.error('Failed to fetch trending topics:', error);
        trendingTopics.value = [];
      }
    }

    // Generate suggested questions
    async function generateSuggestedQuestions() {
      try {
        suggestedQuestions.value = [{ text: '小莒正在思考中..' }];
        
        const token = uni.getStorageSync('token') || '';
        const res = await uni.request({
          url: 'https://tushuoit.com/api/ju/shikong/suggested-questions',
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'Authorization': token ? `Bearer ${token}` : ''
          },
          data: {
            figure_description: currentFigure.value.description || '',
            trending_topics: trendingTopics.value,
            user_profile: userProfile.value
          }
        });

        if (res.statusCode === 200 && res.data.code === 0) {
          suggestedQuestions.value = res.data.data || getDefaultQuestions();
        } else {
          suggestedQuestions.value = getDefaultQuestions();
        }
      } catch (error) {
        console.error('Failed to generate suggested questions:', error);
        suggestedQuestions.value = getDefaultQuestions();
      }
    }

    // Get default questions based on current figure
    function getDefaultQuestions() {
      return [
        { text: `你能介绍一下你的主要成就吗？` },
        { text: `你对${currentFigure.value.title}有什么见解？` },
        { text: `能分享一个关于你的故事吗？` }
      ];
    }

    // Refresh questions periodically (every 5 minutes)
    let refreshInterval;
    onMounted(() => {
      refreshInterval = setInterval(async () => {
        await fetchTrendingTopics();
        await generateSuggestedQuestions();
      }, 5 * 60 * 1000);
    });

    onBeforeUnmount(() => {
      if (refreshInterval) {
        clearInterval(refreshInterval);
      }
    });

    return {
      currentFigure,
      messages,
      userInput,
      isLoading,
      isStreaming,
      scrollTop,
      goBack,
      renderMarkdown,
      sendMessage,
      scrollToBottom,
      containerHeight,
      inputAreaHeight,
      handleTextareaHeightChange,
      textArea,
      clearChatHistory,
      suggestedQuestions,
      handleQuestionClick,
      generateSuggestedQuestions
    };
  }
});
</script>

<style>
.container {
  position: relative;
  box-sizing: border-box;
  height: 100vh;
  background-color: #f8f3e9;
}

.header {
  background-color: #ffffff;
  /* padding: 15px; */
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  height: 55px;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  border-bottom: 1px solid #e9d8bc;
}

.back-button {
  width: 30px;
  height: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.back-icon {
  font-size: 24px;
  color: #3a2c1d;
}

.figure-info {
  flex: 1;
  text-align: center;
}

.figure-name {
  font-size: 18px;
  font-weight: bold;
  color: #3a2c1d;
  display: block;
}

.figure-title {
  font-size: 12px;
  color: #7d6e5d;
}

.chat-container {
  /* flex: 1; */
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  /* padding: 0 15px 0 15px; */
  box-sizing: border-box;
}

.message-wrapper {
  display: flex;
  flex-direction: column;
  padding: 15px;
  /* margin: 15px; */
}

.message-item {
  display: flex;
  margin-bottom: 15px;
  max-width: 90%;
  /* Increase from 80% to give more space */
  align-items: flex-start;
  /* Align items to the top */
}

.message-item.user {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.message-item.figure {
  align-self: flex-start;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin: 0 10px;
  flex-shrink: 0;
  /* Prevent avatar from shrinking */
  overflow: hidden;
  /* Ensure content is clipped to the rounded borders */
}

.message-avatar image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  /* Make sure the image covers the area properly and maintains aspect ratio */
}

.message-content {
  padding: 12px;
  border-radius: 12px;
  word-break: break-word;
  font-size: 16px;
  line-height: 1.5;
  min-width: 40px;
  /* Ensure messages have minimum width */
  max-width: calc(100% - 70px);
  /* Ensure content doesn't overflow considering avatar + margins */
}

.figure .message-content {
  background-color: #ffffff;
  color: #3a2c1d;
  border: 1px solid #e9d8bc;
}

.user .message-content {
  background-color: #e0c9a6;
  color: #3a2c1d;
}

.bottom-container {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ffffff;
  border-top: 1px solid #e9d8bc;
}

.input-area {
  display: flex;
  padding: 15px;
  align-items: center;
}

.input-preset {
  height: var(--ai-chat-input-preset-height, 40px);
  padding: 0 15px;
  display: flex;
  align-items: center;
  gap: 2.133vw;
  overflow: hidden;
  border-bottom: 1px solid rgba(233, 216, 188, 0.5);
}

.preset-scroll {
  width: 100%;
  white-space: nowrap;
}

.preset {
  display: flex;
  align-items: center;
  gap: 2.133vw;
  padding-right: 3.2vw;
}

.preset-item {
  flex: none;
  padding: 1.333vw 3.2vw;
  border-radius: 5.333vw 0 5.333vw 5.333vw;
  background-color: var(--ai-primary-color, rgba(139, 107, 74, 0.1));
  color: #8b6b4a;
  font-family: PingFang SC;
  font-size: 3.467vw;
  font-weight: 400;
  line-height: 4.8vw;
  white-space: nowrap;
  cursor: pointer;
  transition: all 0.3s ease;
}

.preset-item:active {
  opacity: 0.8;
}

.input-box {
  flex: 1;
  background-color: #f8f3e9;
  border-radius: 20px;
  padding: 10px 15px;
  font-size: 16px;
  max-height: 100px;
  min-height: 40px;
}

.send-button {
  margin-left: 10px;
  background-color: #a38d6d;
  color: white;
  width: 60px;
  height: 40px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.send-button.disabled {
  background-color: #ccc;
  opacity: 0.7;
}

.send-text {
  font-size: 16px;
}

.typing-indicator {
  display: flex;
  padding: 12px;
  background-color: #ffffff;
  border-radius: 12px;
  width: 60px;
  justify-content: center;
  align-self: flex-start;
  margin-left: 60px;
}

.typing-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #a38d6d;
  margin: 0 3px;
  animation: typing 1.5s infinite ease-in-out;
}

.typing-dot:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0% {
    transform: translateY(0);
  }

  50% {
    transform: translateY(-5px);
  }

  100% {
    transform: translateY(0);
  }
}

/* Add styles for markdown content */
.message-content img {
  max-width: 100%;
  border-radius: 8px;
}

.message-content p {
  margin-bottom: 8px;
}

.message-content ul,
.message-content ol {
  padding-left: 20px;
  margin-bottom: 8px;
}

.message-content code {
  background-color: rgba(0, 0, 0, 0.05);
  padding: 2px 4px;
  border-radius: 4px;
  font-family: monospace;
}

.message-content pre {
  background-color: rgba(0, 0, 0, 0.05);
  padding: 8px;
  border-radius: 4px;
  overflow-x: auto;
  margin-bottom: 8px;
}

.message-content blockquote {
  border-left: 3px solid #a38d6d;
  padding-left: 8px;
  color: #666;
  margin: 8px 0;
}

.message-content table {
  border-collapse: collapse;
  width: 100%;
  margin-bottom: 10px;
}

.message-content th,
.message-content td {
  border: 1px solid #ddd;
  padding: 6px;
}

.message-content th {
  background-color: #f2f2f2;
}

/* Add specific styles for markdown rendered by rich-text */
.markdown-content {
  width: 100%;
}

/* We need to style the rich-text rendered elements using these global selectors */
.figure .message-content rich-text {
  width: 100%;
}

.user .message-content rich-text {
  width: 100%;
}

/* Add global styles that will affect the HTML inside rich-text */
/* Note: These might have limited effect due to rich-text's shadow DOM encapsulation */
.message-content rich-text img {
  max-width: 100%;
  border-radius: 8px;
}

.message-content rich-text p {
  margin-bottom: 8px;
}

.message-content rich-text ul,
.message-content rich-text ol {
  padding-left: 20px;
  margin-bottom: 8px;
}

.message-content rich-text code {
  background-color: rgba(0, 0, 0, 0.05);
  padding: 2px 4px;
  border-radius: 4px;
  font-family: monospace;
}

.message-content rich-text pre {
  background-color: rgba(0, 0, 0, 0.05);
  padding: 8px;
  border-radius: 4px;
  overflow-x: auto;
  margin-bottom: 8px;
}

.message-content rich-text blockquote {
  border-left: 3px solid #a38d6d;
  padding-left: 8px;
  color: #666;
  margin: 8px 0;
}

.message-content rich-text table {
  border-collapse: collapse;
  width: 100%;
  margin-bottom: 10px;
}

.message-content rich-text th,
.message-content rich-text td {
  border: 1px solid #ddd;
  padding: 6px;
}

.message-content rich-text th {
  background-color: #f2f2f2;
}

/* Update markdown styles to match zhixun/index.vue */
.markdown-content {
  width: 100%;
}

/* Markdown styles */
.markdown-content h1,
.markdown-content h2,
.markdown-content h3,
.markdown-content h4,
.markdown-content h5,
.markdown-content h6 {
  margin-top: 16px;
  margin-bottom: 8px;
  font-weight: 600;
  line-height: 1.25;
}

.markdown-content h1 {
  font-size: 20px;
}

.markdown-content h2 {
  font-size: 18px;
}

.markdown-content h3 {
  font-size: 16px;
}

.markdown-content p {
  margin-bottom: 10px;
}

.markdown-content ul,
.markdown-content ol {
  margin-bottom: 10px;
  padding-left: 20px;
}

.markdown-content ul {
  list-style-type: disc;
}

.markdown-content ol {
  list-style-type: decimal;
}

.markdown-content li {
  margin-bottom: 5px;
}

.markdown-content code {
  background-color: #f1f1f1;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: monospace;
}

.markdown-content pre {
  background-color: #f6f8fa;
  padding: 10px;
  border-radius: 5px;
  overflow-x: auto;
  margin-bottom: 10px;
}

.markdown-content blockquote {
  border-left: 3px solid #dfe2e5;
  padding-left: 10px;
  color: #6a737d;
  margin: 0 0 10px;
}

.markdown-content a {
  color: #007aff;
  text-decoration: underline;
}

.markdown-content img {
  max-width: 100%;
  margin: 10px 0;
}

.markdown-content table {
  border-collapse: collapse;
  width: 100%;
  margin-bottom: 10px;
}

.markdown-content table th,
.markdown-content table td {
  border: 1px solid #ddd;
  padding: 8px;
}

.markdown-content table th {
  background-color: #f6f8fa;
  font-weight: bold;
}

/* Adapt styles for figure/user messages */
.figure .markdown-content {
  color: #3a2c1d;
}

.user .markdown-content {
  color: #3a2c1d;
}

/* Add styles for the clear history button (copied from zhixun/chat.vue) */
.clear-history-button {
  display: flex;
  justify-content: center;
  margin: 10px 0;
}

.clear-history-text {
  background-color: rgba(139, 107, 74, 0.1);
  color: #8b6b4a;
  font-size: 14px;
  padding: 6px 12px;
  border-radius: 15px;
  border: 1px solid rgba(139, 107, 74, 0.2);
}
</style>
